import axios from 'axios'
import service from './api'
// service 循环遍历输出不同的请求方法
import { Loading } from 'element-ui';

// 创建axios 实例  ===> 代理服务器一定要写/!!!!
let instance = axios.create({
	baseURL: '/dev_api',
	withCredentials: true, // send cookies when cross-domain requests
	timeout:5000,
})
const Request = {} // 包裹请求方法的容器
// 请求格式参数的统一
for (let key in service){
	let api = service[key]; // url + method
	// async 作用异步操作  避免进入回调地狱
	Request[key] = async function(
		params, // 请求参数 get delete ==> url  post put patch ==> data
		isFormData = false,// 标识是否是formdata
		config={}       //
		// 配置参数
	){
		let newParams = {} // 默认第一个参数
		// 处理文件是form-data 的情况
		if (params && isFormData){
			let newParams = new FormData();
			for(let i in params){
				newParams.append(i,params[i]);
			}
		}else {
			newParams = params
		}

		let response={}; //回复
		// post / put /patch 请求
		if(api.method === 'post' || api.method === 'put' || api.method === 'patch' ){

			try {
				response = await instance[api.method](api.url,newParams,config)
			}catch (err){
				response = err ;
			}}else if (api.method === 'delete' || api.method === 'get'){
			config.params = newParams
			try {
				response = await instance[api.method](api.url,config)
			}catch (err){
				response = err;
			}
		}
		return response; // 返回响应值
	}

}
// 拦截器的添加
// loading
// let loadingInstance;
// 请求拦截器
instance.interceptors.request.use(config =>{
	// 发起请求前loading
	// loadingInstance = Loading.service();
	return config
}, () =>{
	// 请求错误
})

// 响应拦截器
instance.interceptors.response.use(res =>{
	// 请求成功后 去除loading
	// loadingInstance.close();
	return res.data;
}, err =>{
	console.log(err) ;
})

export default Request;
